<template>
	<el-dialog :visible.sync="addVisible" @close="$emit('update:addVisible',false)" width="70%" :show-close='false' :append-to-body = "true" class="titrationDialog" :closeOnClickModal='false'>
        <span slot="title" class="dialog-title">
            标定结果
            <el-button size="mini"  @click="close"  class="popupClose">关闭</el-button>

        </span>
		<div style = "height:100%;">
			<el-button size="mini" type = "primary" style = "float:right;margin-bottom:10px;" @click = "addsample">添加</el-button>
			<el-table :data="titrationData"  size="mini"  style = "width: 100%;" :height = "tableHeight" class = "tableCon" show-summary :summary-method="getSummaries" >
				<el-table-column label="序号" min-width="50px" >
					<template slot-scope="scope" >
						{{scope.$index+1}}
					</template>
				</el-table-column>
				<el-table-column label="样品编号" min-width="120px" prop = "sampleCode" >
				</el-table-column>
				<template v-for="(col,index) in titrationList" >
					<el-table-column  :prop="col.id"  :key="index" min-width= "120px" align="center" :render-header="(h,obj) => labelHead(h,obj,col)">
						<el-table-column :label="col.unitName == undefined ? '---' : col.unitName" width="160px" :prop="col.id" :index = " col.type">
                            <template slot-scope="scope">
								<el-input  v-model="scope.row[col.id]" size="mini"
								v-if = "col.formula == undefined || col.formula == null || col.formula == ''"
								 @blur ="countFormula(scope.row)"
								 oninput="this.value=this.value.replace(/[^0-9.]+/,'');" class = "deal"></el-input>
								<span v-if="col.formula != undefined && col.formula != null && col.formula != ''">{{scope.row[col.id]}}</span>
							</template>
					 	</el-table-column>
					</el-table-column>
				</template>
				<el-table-column  label="操作" min-width="80px" >
					 <template slot-scope="scope">
						<el-button size="mini" type="text"  @click="deleteSample(scope.$index)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		 <span slot="footer" class="dialog-footer" >
            <el-button type="primary" size="mini" @click="subTitration">确定</el-button>
            <el-button size="mini" @click="close()">取 消</el-button>

        </span>

	</el-dialog>
</template>

<script>
	import $ from 'jquery'
	import { mapState } from 'vuex'

	export default {
		data() {
			return {
				titrationData:[], //样品列表
				titrationVal:{},
				enterFlag: false,
				average:0,
				showSum:false,
				batchCode:'',
				codeObj:new Set(),


			}
		},
		watch: {

		},
		props: ['addVisible','testEntryData','titrationList'],
		components: {

		},
		mounted() {
			console.log(this.testEntryData)
		},
		computed: {
			...mapState(['tableHeightA']),
			tableHeight(){
				return ((window.innerHeight * 0.8) - 150) + 'px'
			}

		},
		watch:{
			addVisible(val){
				if(val){
					console.log(this.titrationList)
					var code = this.testEntryData.code;
					this.batchCode = code.replace(/BA/g,"") + '00';
					this.getCalib();
				}
			},
			enterFlag(val){
				for(var i in this.titrationData){
					this.countFormula(this.titrationData[i]);
				}
			},
		},
		methods: {
			close(){
				this.codeObj = new Set();
				this.titrationData = [];
				this.$emit('update:addVisible', false);
			},


			//
			// 样品
			getCalib(){
				var data = {
					batch:this.testEntryData.id,
					detectability:this.testEntryData.detectability,
				}
				this.$http({
					method: 'post',
					apiUrl: '/detection/getCalib.htm',
					params: data,
					isJson: true,
				}).then(res => {
					if (res.code === 0) {
            for(var i in res.data.listVal){
              if(res.data.listVal[i].id == undefined || res.data.listVal[i].id == null ||  res.data.listVal[i].id == ""){
                var sampleCode = this.changeCode();
                this.$set(res.data.listVal[i],'sampleCode',sampleCode)
              }
            }
						this.titrationData = res.data.listVal;


						this.titrationVal =  res.data
						this.enterFlag = !this.enterFlag
						this.reload();
					}
				})
			},

			changeCode(){ //生成样品编码
				var batchCode = this.testEntryData.code.replace(/BA/g,"") + '00';
				var len = this.titrationData.length + 1;
				var code1 = Number(batchCode) + Number(len);
				for(var i in this.titrationData){
					var size = this.codeObj.size;
					var code = Number(this.titrationData[i].sampleCode.replace(/B/g,""));
					this.codeObj.add(code);
				}
				// 判断新编码是否已经存在，不存在加入进去，存在的话依次加1知道不存在
				while(this.codeObj.has(code1))
				{
					code1 ++
				}
				this.codeObj.add(code1)
				// 把1对象转换位数字，取最后一个值
				var setArr = Array.from(this.codeObj);
				var sampleCode = Number(setArr[setArr.length - 1])
				sampleCode = "B" + sampleCode;
				return sampleCode;
			},
			addsample(){

				var obj = {
					sampleCode:this.changeCode(),
				};
				console.log(this.titrationList)
				for(var i in this.titrationList){
					// formula
					if(this.titrationList[i].formula == undefined || this.titrationList[i].formula == '' || this.titrationList[i].formula == null){
						this.$set(obj,this.titrationList[i].id,this.titrationList[i].defaultValue);
					}else{
						this.$set(obj,this.titrationList[i].id,null);
					}


				}
				console.log(obj)
				this.titrationData.push(obj)
				this.enterFlag = !this.enterFlag
				this.codeObj = new Set();
			},
			labelHead(h, {
				column,
				index
			},col) {
				console.log(col)
				if(col.formula != undefined && col.formula != null && col.formula != ''){
					return [
						column.label,
						h(
						'el-tooltip',
						{
							props: {
								content: (function() {
									return col.formulaName
								})(),
								placement: 'top'
							}
						},
						[
							h('div', {
								class: {
									'cell': true
								}
							},[col.name])
						]
						)
					]
				}else{
					return [
						column.label,
						// h(
						// 'el-tooltip',
						// {
						// 	props: {
						// 		content: (function() {
						// 			return 111
						// 		})(),
						// 		placement: 'top'
						// 	}
						// },
						// [
							h('div', {
								class: {
									'cell': true
								}
							},[col.name])
						// ]
						// )
					]
				}

			},
			deleteSample(index){

				this.titrationData.splice(index,1)
				this.enterFlag = !this.enterFlag
			},
			// 计算公式
			countFormula(row){
				var formulaArr = []
				var sum = 0; //用来计算平均数的总数

			    for(var i in this.titrationList){ //找出需要计算的列
					if(this.titrationList[i].formula != undefined && this.titrationList[i].formula != '' && this.titrationList[i].formula != null){ //找出有公式的列
						var arr = this.titrationList[i].formula.split(",") //将公式拆分为数组
						var codesFlag = 1;
						var isThreeMesh = false;
						for (var j in arr) { //遍历一个公式的字符，并存储code到 codeArr数组中
							if (arr[j] == "?") { //判断是否是三目运算
								isThreeMesh = true;
							}
							if (arr[j].substr(0, 1) == "{") { //获取检测项目或者分析项的code，并替换为值
								var code = arr[j].replace(/{/g, '');
								code = code.replace(/}/g, '');   //公式中的code
								var f = false; //解析标志
								for (var k in this.titrationList) { //遍历所有的表头，目的是匹配公式中的code
									if (code == this.titrationList[k].code) { //取公式中的code和其他表头的code对比，如果分析项和检测项的公式用到失去焦点这一行的code 则根据公式给分析项和检测项赋值
										f = true;
										var propId = this.titrationList[k].id
										if(row[propId] !== null && row[propId] !== undefined && row[propId] !== ''){
											codesFlag = codesFlag * 1; //表明被替换
											arr[j] = row[propId]
										}else{
											codesFlag = codesFlag * 0; //表明没有被替换
										}
									}
								}
								if (!f) {
									this.$notify({
										title: "警告",
										message: '公式无法正确解析,请到技术标准检查公式!',
										type: "warning"
									})
									return;
								}
							}
						}
						if (codesFlag == 1) {
							 var formu = null;
							if (isThreeMesh) { //判断三目运算符号 A == B ? C :D
								var a = null,
								b = null,
								c = null;
								for (var k in arr) {
									if (arr[k] == "==") { //==的位置
										a = k;
									}
									if (arr[k] == "?") { //?的位置
										b = k;
									}
									if (arr[k] == ":") { //:的位置
										c = k;
									}
								}
								var A = arr.slice(0, a);
								var aa = eval(A.join().replace(/,/g, ''));
								var B = arr.slice(Number(a) + 1, b);
								var bb = eval(B.join().replace(/,/g, ''));
								var C = []; //最终的计算公式
								if (aa == bb) {
								C = arr.slice(Number(b) + 1, c);

								} else {
								C = arr.slice(Number(c) + 1, arr.length);
								}
								formu = C.join().replace(/,/g, '');
							}else{
								formu = arr.join().replace(/,/g, '');
							}

							// 判断计算后的公式是否是小数，如果是整数 直接赋值，如果是小数，判断小数点后位数 如果大于6位则保留6位，小于6位则全部保留

							var lastResult = Number(this.$math.parser().eval(formu));
							lastResult = this.evenRound(lastResult,this.titrationList[i].decimalNumber)

							row[this.titrationList[i].id] = lastResult
						}else{
							row[this.titrationList[i].id] = "";
						}

					}

				}

			},
			reload(){
				this.showSum=false;
				this.$nextTick().then(()=> {
					this.showSum=true;
				});
			},
			getSummaries(param) {
				const { columns, data } = param;
				const sums = [];
				this.average = 0;
				console.log( param)
				columns.forEach((column, index) => {
					if (index === 0) {
						sums[index] = '平均值';
						return;
					}
					if (index === 1) {
						sums[index] = '---';
						return;
					}
					const values = data.map(item => Number(item[column.property]));
					if (column.index == 4 && !values.every(value => isNaN(value))) {
						sums[index] = values.reduce((prev, curr) => {
							const value = Number(curr);
							if (!isNaN(value)) {
								return prev + curr;
							} else {
								return prev;
							}
						}, 0);
						var formu =  sums[index] + "/" + this.titrationData.length;
						sums[index] = Number(this.$math.parser().eval(formu));
						var num = Number(index - 2);
						sums[index] = this.evenRound(sums[index],this.titrationList[num].decimalNumber)
						this.average = sums[index]

					} else {
						sums[index] = '---';
					}
				});
				return sums;
			},
			// 四舍六入五成双
			evenRound(value, number) {
				var d = number || 0;
				var m = Math.pow(10, d);
				var n = Number(+(d ? value * m : value)).toFixed(8); // Avoid rounding errors
				var i = Math.floor(n),
					f = n - i;
				var e = 1e-8; // Allow for rounding errors in f
				var r = (f > 0.5 - e && f < 0.5 + e) ?
					((i % 2 == 0) ? i : i + 1) : Math.round(n);
				var res = d ? r / m : r;
				//  console.log(res)
				res = res.toFixed(number);
				return res;
			},
			subTitration(){
				console.log(this.average)
				var data = {
					batch:this.testEntryData.id,
					avg:this.average,
					equipment:this.testEntryData.equipment,
					listAnal:this.titrationList,
					listVal:this.titrationData,
				}
				if(this.titrationVal.id != undefined){
					data.id = this.titrationVal.id
				}
				console.log(data)
				this.$http({
					method: 'post',
					apiUrl: '/detection/addCalib.htm',
					params: data,
					isJson: true,
				}).then(res => {
					if (res.code === 0) {
						this.close()
						// this.titrationData = res.data.listVal;
					}

				})

			},


		}
	}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
	.titrationDialog .el-dialog {
		margin-top: 10vh !important;
		height: 80%;
	}
/*
	.titrationDialog .el-dialog__body {
		height: calc(100% - 75px);
		overflow-y: auto;
	}*/

	.titrationDialog .el-dialog .el-dialog__body {
		height: calc(100% - 85px);
		padding: 10px;
		overflow-y: auto;
	}
	.titrationDialog .el-table{
		overflow: auto !important;
	}
	.titrationDialog .el-table__fixed-body-wrapper{
		top:68px !important;
	}
	.titrationDialog .tableCon .el-table__body-wrapper{
		height: calc(100% - 105px) !important;
	}
	.titrationDialog .tableCon.el-table td {
		padding: 6px !important;
	}
	.titrationDialog .el-table__footer-wrapper{
		margin-top:-6px;
	}

</style>
